<?php
if (!defined('__COLA_DIR__')) exit;
/**
 * 下拉选择框帮手
 *
 * @author edikud
 * @package Form
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */

class Form_Select extends Form_Group
{
    /**
     * 选择值
     *
     * @access private
     * @var array
     */
    private $_options = array();

    /**
     * 初始化当前输入项
     *
     * @access public
     * @param string $name 表单元素名称
     * @param array $options 选择项
     * @return Element
     */
    public function input($name = NULL, array $options = NULL)
    {
        $input = new Element('select', array(
		    'id' => 'input-' . self::$uniqueId, 
			'name' => $name, 
			'class' => 'form-control'));
        $this->set($input);
        $this->label->setAttr('for', 'input-' . self::$uniqueId);

        foreach ($options as $value => $label) {
            $this->_options[$value] = new Element('option');
            $input->set($this->_options[$value]->setAttr('value', $value)->set($label));
        }

        return $input;
    }

    /**
     * 设置表单元素值
     *
     * @access protected
     * @param mixed $value 表单元素值
     * @return void
     */
    protected function _value($value)
    {
        foreach ($this->_options as $option) {
            $option->removeAttr('selected');
        }

        if (isset($this->_options[$value])) {
            $this->_options[$value]->setAttr('selected', 'true');
        }
    }
}
